const colors = require('colors');
const { formatDate } = require('../utils');
const { STATUS_CODE } = require('../constants');

/**
 *
 * @param {*} message number | string | object
 * @returns { code, field, message }
 */
const parseErrorMessage = errorMessage => {
  err = JSON.parse(errorMessage);
  const is = typeof err === 'string' || typeof err === 'number';
  const code = is ? err : err.code;
  const field = is ? '' : err.field;
  const message = is ? '' : err.message;

  return { code: Number(code), field, message };
};
const errorMiddleware = (error, ctx) => {
  // debug log
  console.error(`${formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss')} error middleware caught eror`.red);
  console.error(error);

  const { code, field, message } = parseErrorMessage(error.message);

  let resp = { code: STATUS_CODE.ERROR };
  switch (code) {
    case STATUS_CODE.PARAMS_ERROR:
      ctx.response.status = 400;
      resp = {
        code: 400,
        message: 'bad quest',
      };
      break;
    case STATUS_CODE.UNAUTHORIZED:
      ctx.response.status = 401;
      resp = {
        code: 401,
        message: 'unauthorized',
      };
      break;
    case STATUS_CODE.FORBIDDEN:
      ctx.response.status = 403;
      resp = {
        code: 403,
        message: 'forbidden',
      };
      break;
    case STATUS_CODE.FIELD_LENGTH_ERROR:
      resp = {
        code: STATUS_CODE.FIELD_LENGTH_ERROR,
        message: `bad request，${field} length error`,
      };
      break;
    case STATUS_CODE.PARAMS_TYPE_ERROR:
      resp = {
        code: STATUS_CODE.PARAMS_TYPE_ERROR,
        message: `${field} type error!`,
      };
    case STATUS_CODE.USER_ALREADY_EXIST:
      resp = {
        code: STATUS_CODE.USER_ALREADY_EXIST,
        message: 'user already exist!',
      };
      break;
    case STATUS_CODE.PASSWORD_ERROR:
      resp = {
        code: STATUS_CODE.PASSWORD_ERROR,
        message: 'user password error!',
      };
      break;
    default:
      resp = {
        code: 500,
        message: 'system error',
      };
  }
  if (message) {
    resp.message = message;
  }
  ctx.body = resp;
};

module.exports = errorMiddleware;
